#include "file.h"
#include <cjson/cJSON.h>
#include <mosquitto.h>
#include <stdlib.h>
#include <unistd.h>  //sleep
#include <stdio.h>
#include <string.h> //strlen

const char* topic_pub = "1718787027582/Device2AIOTSIM";
const char* topic_sub = "1718787027582/AIOTSIM2Device";
const char* led_path = "/sys/class/leds/led1/brightness";
const char* client_id = "askduhkegfeiuw";

//消息处理函数
void on_message(struct mosquitto * client, void * data, const struct mosquitto_message * msg)
{
    printf("Topic: %s\n", msg->topic);
    //打印消息主题
    if (strcmp(msg->topic, topic_sub))
    {
        //不是订阅的主题
        printf("Topic: %s\n", msg->topic);
    }
    //将JSON字符串转为C的结构体
    cJSON* obj = cJSON_ParseWithLength(msg->payload, msg->payloadlen);
    if (!obj)
    {
        //JSON字符串解析失败
        printf("JSON: %*s\n", msg->payloadlen, msg->payload);
        return;
    }
    printf("JSON: %*s\n", msg->payloadlen, msg->payload);
    cJSON* lamp = cJSON_GetObjectItem(obj, "lamp");
    if (!lamp)
    {
        printf("lamp property not found\n");
        return;
    }

    if (cJSON_IsTrue(lamp))
    {
        //开灯
        write_file(led_path, "1");
    }

    if (cJSON_IsFalse(lamp))
    {
        //关灯
        write_file(led_path, "0");
    }
}

int main()
{
    //初始化函数库
    mosquitto_lib_init();

    //创建客户端
    struct mosquitto* client = mosquitto_new(client_id, true, NULL);
    if (!client)
    {
        perror("mosquitto_new");
        mosquitto_lib_cleanup();
        return EXIT_FAILURE;
    }

    //注册消息处理函数
    mosquitto_message_callback_set(client, on_message);

    //连接服务器
    int error = mosquitto_connect(client, "mqtt.yyzlab.com.cn", 1883, 60);
    if (error != MOSQ_ERR_SUCCESS)
    {
        printf("mosquitto_connect: %s\n", mosquitto_strerror(error));
        mosquitto_destroy(client);
        mosquitto_lib_cleanup();
        return EXIT_FAILURE;
    }

    printf("connected to MQTT broker\n");

    //订阅主题
    error = mosquitto_subscribe(client, NULL, topic_sub, 0);
    if (error != MOSQ_ERR_SUCCESS)
    {
        printf("mosquitto_subscribe: %s\n", mosquitto_strerror(error));
    }

    //启动心跳线程
    mosquitto_loop_start(client);

    while(1)
    {
        sleep(5);
    }

    mosquitto_loop_stop(client, false);

    //销毁客户端
    mosquitto_destroy(client);

    //清理函数库
    mosquitto_lib_cleanup();

    return EXIT_SUCCESS;
}